package app.controllers.admin.sys;

import app.dtos.CurrencyToIntegral;
import app.models.sys.Currency;
import com.alibaba.fastjson.JSON;
import com.github.sog.controller.AjaxMessage;
import com.github.sog.controller.BasicController;
import com.github.sog.plugin.sqlinxml.SqlKit;
import com.google.common.base.Strings;

import java.util.Date;


/**
 * <p>
 * .
 * </p>
 *
 * @author Jerry Ou
 * @version 1.0 2014-02-12 13:41
 * @since JDK 1.6
 */
public class CurrencyController extends BasicController {

    public void index() {
        Currency currency = Currency.dao.findFirst(SqlKit.sql("currency.list"));
        if (currency == null) {
            currency = new Currency();
        }

        String json = currency.getStr("rule");
        CurrencyToIntegral cti = new CurrencyToIntegral();
        if (!Strings.isNullOrEmpty(json)) {
            cti = JSON.parseObject(json, CurrencyToIntegral.class);
        }
        setAttr("cti", cti);
        setAttr("currency", currency);

        render("index.ftl");
    }

    private double parseDouble(String str) {
        double val = 0;
        if (!Strings.isNullOrEmpty(str)) {
            val = Double.parseDouble(str);
        }
        return val;
    }

    public void save(){
        String currencyStr = getPara("currency");
        String integralStr = getPara("integral");
        double currency = parseDouble(currencyStr);
        double integral = parseDouble(integralStr);
        CurrencyToIntegral currencyToIntegral = new CurrencyToIntegral();
        currencyToIntegral.currency = currency;
        currencyToIntegral.integral = integral;
        String json = JSON.toJSONString(currencyToIntegral);

        long id = getParaToLong("id", 0l);
        Currency c = new Currency();
        c.set("name", "中南币转积分");
        c.set("rule", json);
        if (id == 0) {
            c.set("create_time", new Date());
            c.save();
        } else {
            c.set("id", id);
            c.update();
        }
        renderJson(AjaxMessage.ok("保存成功"));
    }

}
